#include <iostream>
#include "color.h"
#include "vec3.h"
#include "ray.h"

// https://raytracing.github.io/books/RayTracingInOneWeekend.html

color ray_color(const ray& r){
    vec3 unit_direction = unit_vector(r.direction());
    auto t  = 0.5 *(unit_direction.y() + 1.0);// 归一化
    return (1.0 - t)*color(1.,1.,1.) + t* color(0.5, 0.7, 1.0);//mix
}
int main(){
    // image 类似canvas
    int image_width = 400;
    auto aspect_ratio = 16.0/9.0;
    // 计算高度，不低于1 像素
    int image_height = int( image_width/aspect_ratio);
    image_height = (image_height <1)?1:image_height;
    //  camera
    auto focal_length = 1.0; // 焦距 可是哪里来的焦距

    auto viewport_height = 2.0;
    auto viewport_width = viewport_height *(double(image_width/image_height));
    auto camera_center = point3(0,0,0);
    // ray
    point3 origin = point3(0,0,0);
    vec3  horizontal = vec3(viewport_width,0.0,0);
    vec3 vertical = vec3(0,viewport_height,0);
    // 看来焦距就是 相机到栅格面的距离了
    point3 lower_left_coner = origin - horizontal/2 - vertical/2 - vec3(0,0,focal_length);
    
// 文件头部 声明图片宽高
    std::cout << "P3\n" + std::to_string(image_width) + " " + std::to_string(image_height) + "\n255\n";
    for (int j =  image_height -1; j >=0; --j)
    {
        std::clog << "Processing row " << j << "\n"<< std::flush ;
        for (int i = 0; i < image_height; i++)
        {
           auto u = float(i)/(image_width -1); 
           auto v = float(j)/(image_height -1); 
        //    这就相当于搞了一个阴极射线扫描枪啊  还要减 origin是因为第二个参数是方向
            ray r(origin,lower_left_coner + v *vertical + u*horizontal -origin);
            color pixel_color = ray_color(r);

           write_color(std::cout, pixel_color);
        }
        /* code */
    }
    std::clog << "Done.\n";
    return 0;
}